<template>
  <div>
    <a class="btn" @click="toggleShow">set avatar</a>
    <jm-image-uploader
      v-loading="isLoading"
      v-show="show"
      :width="200"
      :height="200"
      :allow-img-format="['png', 'jpg', 'svg']"
      @toUpload="toUpload"
      :radius="50"
      :remote-img-url="'https://portrait.gitee.com/uploads/avatars/user/2602/7807504_comyan_1629190959.png!avatar200'"
    />
  </div>
</template>

<script lang="ts">
import { defineComponent, getCurrentInstance, ref } from 'vue';
import * as qiniu from 'qiniu-js';
export default defineComponent({
  name: '',
  setup() {
    const isLoading = ref(false);
    const { $success } =
      getCurrentInstance().appContext.config.globalProperties;
    const show = ref(false);
    // 调用获取token的api
    const token = ref(
      'di0QoZTUFcBPUenjPF2jco9ewZR6nEHkR8kom_xv:H9DO1H5Z86FXlFiPxs9vV-AqI08=:eyJjYWxsYmFja0JvZHlUeXBlIjoiYXBwbGljYXRpb24vanNvbiIsImNhbGxiYWNrQm9keSI6IntcImtleVwiOlwiJChrZXkpXCIsXCJoYXNoXCI6XCIkKGV0YWcpXCIsXCJmc2l6ZVwiOiQoZnNpemUpLFwiYnVja2V0XCI6XCIkKGJ1Y2tldClcIixcIm5hbWVcIjpcIiQoeDpuYW1lKVwiLFwiZXh0cmFjdFwiOlwiJCh4OnRlc3QpXCJ9Iiwic2NvcGUiOiJ0ZXN0LWppYW5tdSIsImRlYWRsaW5lIjoxNzA2OTgxODQ4fQ=='
    );
    // 具体OOS上传
    const toUpload = file => {
      // 获取上传文件
      const observer = {
        // 七牛上传过程中执行的回调
        next() {},
        error() {},
        // 七牛云上传成功后的回调
        complete() {
          isLoading.value = true;
          setTimeout(() => {
            isLoading.value = false;
            show.value = false;
            $success('图片上传成功！');
          }, 2000);
        },
      };
      const config = {
        // 启用cdn加速
        useCdnDomain: true,
        // 设置的上传域（华北）
        region: qiniu.region.z1,
      };
      // 上传开始
      qiniu
        .upload(
          file,
          // 这里就采用七牛云默认的hash命名，cdn有缓存同样的名字，即使在七牛云删除了对应的文件再次上传同样名字的文件，还是应用的原来图片的地址
          null,
          // Date.now() + '' + this.filename,
          token.value,
          null,
          config
        )
        .subscribe(observer);
    };
    const toggleShow = () => {
      show.value = !show.value;
    };
    return {
      show,
      toggleShow,
      toUpload,
      isLoading,
    };
  },
});
</script>

<style scoped></style>
